package com.listeningframework.boot.commons.math;

import com.listeningframework.boot.commons.string.RegExpUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 
 * Number Utils
 *
 * @author listening
 * @version $Id: NumberUtils.java, v 0.1 2015年10月31日 下午11:25:06 listening Exp $
 */
public class DecimalUtils {
    /**
     * Convert String to BigDecimal
     *
     * @param value 值
     * @return BigDecimal
     */
    public static BigDecimal getDeciaml(String value) {
        if (StringUtils.isBlank(value)) {
            return BigDecimal.ZERO;
        }
        if (!RegExpUtils.isWildDecimal(value.trim())) {
            return BigDecimal.ZERO;
        }
        return new BigDecimal(value.trim());
    }

    /**
     * validate the value between min and max
     *
     * @param value 值
     * @param min 最小
     * @param max 最大
     * @return boolean
     */
    public static boolean size(String value, String min, String max) {
        BigDecimal bdValue = getDeciaml(value);
        BigDecimal bdMin = getDeciaml(min);
        BigDecimal bdMax = getDeciaml(max);
        return gte(bdValue, bdMin) && lte(bdValue, bdMax);
    }

    /**
     * validate if bigdecimal one great than two
     *
     * @param one 被减数
     * @param two 减数
     * @return boolean
     */
    public static boolean gt(BigDecimal one, BigDecimal two) {
        return one.compareTo(two) > 0;
    }

    /**
     * validate if bigdecimal one less than two
     *
     * @param one 数值1
     * @param two 数值2
     * @return boolean
     */
    public static boolean lt(BigDecimal one, BigDecimal two) {
        return one.compareTo(two) < 0;
    }

    /**
     * validate if bigdecimal one great equal than two
     *
     * @param one 数值1
     * @param two 数值2
     * @return boolean
     */
    public static boolean gte(BigDecimal one, BigDecimal two) {
        return one.compareTo(two) >= 0;
    }

    /**
     * validate if bigdecimal one less equal than two
     *
     * @param one 数值1
     * @param two 数值2
     * @return boolean
     */
    public static boolean lte(BigDecimal one, BigDecimal two) {
        return one.compareTo(two) <= 0;
    }

    /**
     * Format Money
     *
     * @param decimal 金额
     * @return String
     */
    public static String formatMoney(BigDecimal decimal) {
        return formatDecimal(decimal, 2);
    }

    /**
     * Format number by scale
     *
     * @param decimal 数值
     * @param scale 有效精度
     * @return String
     */
    public static String formatDecimal(BigDecimal decimal, int scale) {
        BigDecimal tempValue = decimal == null ? BigDecimal.ZERO : decimal;
        return String.valueOf(tempValue.setScale(scale, RoundingMode.HALF_UP));
    }

}
